package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server-admin-api/message"
	"server-admin-api/service"
	"server-admin-api/views"
	"strconv"
)

type CustomizeApi struct {
	service *service.CustomizeService
}

func NewCustomizeApi() *CustomizeApi {
	return &CustomizeApi{
		service: service.NewCustomizeService(),
	}
}

// ServerList 服务列表
func (cus *CustomizeApi) ServerList(c *gin.Context) {
	c.DefaultQuery("page", "1")
	c.DefaultQuery("size", "10")
	var param views.CustomizePageVo
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}

	result, err := cus.service.PageData(param)
	if err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}

	c.JSON(http.StatusOK, message.NewResultMsg().Success(result))
	return
}

// Create 创建
func (cus *CustomizeApi) Create(c *gin.Context) {
	var param views.CustomizeCreate
	c.DefaultQuery("id", "0")
	id, _ := strconv.Atoi(c.Query("id"))
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}
	if err := cus.service.CreateModel(id, param); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("创建服务失败"))
		return
	}
	c.JSON(http.StatusOK, message.NewResultMsg().Success("创建服务成功"))
	return
}

// Run 执行脚本
func (cus *CustomizeApi) Run(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("参数丢失"))
		return
	}
	if err := cus.service.ScriptRun(id); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}
	c.JSON(http.StatusOK, message.NewResultMsg().Success("脚本执行结束"))
	return
}

func (cus *CustomizeApi) Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	if id == 0 {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("参数丢失"))
		return
	}

	if !cus.service.DeleteById(id) {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("删除数据失败"))
		return
	}

	c.JSON(http.StatusOK, message.NewResultMsg().Success("删除数据成功"))
	return
}
